package com.utils
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.getTimer;
	
	public class Design
	{
		private static var design:Design;
		private var _urlLoader:URLLoader;
		private var _waitLoadList:Array = [];//等待加载列表
		private var _designList:Array = [];//数据资源池
		private var _object:Object;
		private var _path:String;//前缀
		private var _prefix:String;//后缀
		private var _loadOver:Function = new Function();//回调
		private var _pk:String;//主键，标记从那里开始写入数据
		
		private var _startTime:int;
		private var _endTime:int;
		private var elems:Array = [];
		private var oneElems:Array = [];
		
		public function Design()
		{
			if(design){
				throw Error('Design不能重复实例化!')
			}else{
				design = this;
			}
			loadXLS(['Struct','name']);
			
			trace('--->创建Design实例!')
			_startTime = getTimer();
		}
		
		public static function instance():Design{
			if(!design) design = new Design();
			return design;
		}
		
		/**加载配置表*/		
		private function loadXLS(list:Array = null ):void{
			_path = list[0];
			_pk = list[1];
			_path == 'Struct' ? _prefix = Path.structPrefix : _prefix = Path.resourcePrefix
			_urlLoader = new URLLoader(new URLRequest(_prefix + _path + Path.extension));
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR,onIO_ERRORHandler);
			_urlLoader.addEventListener(Event.COMPLETE,onLoaderCompleteHandler);
			_urlLoader.addEventListener(ProgressEvent.PROGRESS,onLoadProgressHandler);
		}
		
		/**计算加载进度 */		
		protected function onLoadProgressHandler(e:ProgressEvent):void
		{
		}
		
		private function onIO_ERRORHandler(e:IOErrorEvent):void
		{
			trace('加载出错:' + e);
		}		
		
		private function onLoaderCompleteHandler(e:Event):void
		{
			var excelXml:XML = new XML(e.target.data);
			readData(excelXml);
		}
		
		/**读取配置表数据*/		
		private function readData(excelXml:XML):void{
			var ns:*= excelXml.namespace();
			var rows:*= excelXml..ns::Row;
			var resultList:Array = [];
			var _startWrite:Boolean = false;
			for each (var value:* in rows){
				var list:Array = [];
				var cellData:*=value.ns::Cell.ns::Data.text();
				
				for each (var key:String in cellData) {
					if(key === _pk) _startWrite = true;
					if(_startWrite) list.push(key);
				}
				if(list.length > 0){
					checkList(list,resultList);
				}
			}
			
			if(_path == 'Struct'){
				resultList.shift();
				_waitLoadList = resultList;
			}
			
			for (var j:int = 0; j < resultList.length-1; j++) 
			{
				if(_path != 'Struct') writeData(resultList[0],resultList[j+1]);
			}
			
			if(_waitLoadList.length > 0){
				//trace('----------------------------------------------');
//				trace('waitLoadList:' + _waitLoadList);
				//trace('----------------------------------------------');
				loadXLS(_waitLoadList.shift());
			}else{
				_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR,onIO_ERRORHandler);
				_urlLoader.removeEventListener(Event.COMPLETE,onLoaderCompleteHandler);
				_urlLoader.removeEventListener(ProgressEvent.PROGRESS,onLoadProgressHandler);
				_urlLoader = null;
				_waitLoadList = null;
				_path = '';
				_loadOver();
				
				_endTime = getTimer();
				trace('--->Design数据加载完毕,用时:' + (_endTime - _startTime) + '毫秒!');
			}
		}
		
		/**检查每一项是否为空*/		
		private function checkList(list:Array, resultList:Array):void
		{
			for (var i:int = 0; i < list.length; i++) 
			{
				if(list[i] != ''){
					resultList.push(list);
					return;
				}
			}
		}
		
		/**写入数据 */		
		private function writeData(keyList:Array,valueList:Array):void{
			if(keyList === valueList) return;
			
			var itemObj:Object = new Object();
			var itemString:String = '';
			for (var i:int = 0; i < keyList.length; i++) 
			{
				itemObj[keyList[i]] = valueList[i];
				if(i == keyList.length-1){
					itemString += keyList[i] + ':' + valueList[i];
				}else{
					itemString += keyList[i] + ':' + valueList[i] + ',';
				}
			}
			if(!_designList[_path]){
				_designList[_path] = [];
				_designList[_path].push(itemObj);
			}else{
				_designList[_path].push(itemObj);
			}
			elems.push(itemString);
			
			if(!oneElems[_path]) oneElems[_path] = [];
			oneElems[_path].push(itemString);
		}
		
		/**读取配置信息(数组形式)*/		
		public function load(ExcelName:String):Array{
			return _designList[ExcelName];
		}
		
		/**返回全部加载数据 */		
		public function toString() : String
		{
			return "Design{\n" + elems.join(",\n") + "\n}";
		}
		
		/**返回指定配置表内部数据结构*/		
		public function toStructure(ExcelName:String):String{
			return ExcelName + "{\n" + oneElems[ExcelName].join(";\n") + "\n}";
		}
		
		public function set loadOver(value:Function):void{_loadOver = value;}
		
	}
}

class Path{
	/**数据结构前缀*/	
	public static const structPrefix:String = 'assets/design/doc/';
	/**前缀*/	
	public static const resourcePrefix:String = 'assets/design/resource/';
	/**后缀*/	
	public static const extension:String = '.xml';
	
}



